package com.ruoyi.web.controller.market.account;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.account.enums.AccountTypeEnum;
import com.ruoyi.account.enums.ActionTypeEnum;
import com.ruoyi.account.enums.RecordStatusEnum;
import com.ruoyi.account.model.vo.ApplyRecordVO;
import com.ruoyi.account.service.*;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.AccountItemSpecial;
import com.ruoyi.db.domain.BillInfoChannel;
import com.ruoyi.db.domain.BillInfoProduct;
import com.ruoyi.market.http.model.param.EntryAccountParam;
import com.ruoyi.market.http.service.MarketApiService;
import com.ruoyi.notice.enums.MessageTypeEnum;
import com.ruoyi.notice.service.IMessageNoticeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.db.domain.AccountApplyRecord;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.wapper.AccountApplyRecordWapper;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 账户入账申请Controller
 * 
 * @author ruoyi
 * @date 2023-02-02
 */
@Controller
@RequestMapping("/account/record")
public class AccountApplyRecordController extends BaseController
{
    private String prefix = "account/record";

    @Autowired
    private IAccountApplyRecordService accountApplyRecordService;
    @Autowired
    private IAccountInfoService accountInfoService;
    @Autowired
    MarketApiService marketApiService;
    @Autowired
    private IAccountItemSpecialService accountItemSpecialService;
    @Autowired
    IMessageNoticeService messageNoticeService;

    @RequiresPermissions("account:record:view")
    @GetMapping()
    public String record(ModelMap modelMap)
    {

//        SysUser sysUser = getSysUser();
//        Long[] postIds = sysUser.getPostIds();

        /**
         * 根据用户岗位
         */
//        List<Map<String, String>> accountTypeList = AccountTypeEnum.getListMapByPostId(JSON.parseArray(JSON.toJSONString(postIds), Long.class));
        List<Map<String, String>> accountTypeList = AccountTypeEnum.getListMap();
        modelMap.put("accountTypeList", accountTypeList);

        List<Map<String, String>> actionTypeList = ActionTypeEnum.getListMap();
        modelMap.put("actionTypeList", actionTypeList);

        List<Map<String, String>> statusList = RecordStatusEnum.getListMap();
        modelMap.put("statusList", statusList);

        return prefix + "/record";
    }

    /**
     * 查询账户入账申请列表
     */
    @RequiresPermissions("account:record:view")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AccountApplyRecord accountApplyRecord)
    {

        SysUser sysUser = getSysUser();
        if (!sysUser.isAdmin()){
            accountApplyRecord.setCreatorId(String.valueOf(sysUser.getUserId()));
        }

        startPage();
        List<Map<String, Object>> mapList = accountApplyRecordService.selectAccountApplyRecordListMap(accountApplyRecord);
        mapList = new AccountApplyRecordWapper(mapList).wrap();
        return getDataTable(mapList);
    }

    /**
     * 新增账户入账申请
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        SysUser sysUser = getSysUser();

        // 总账户信息列表
        List<Map<String, Object>> accountInfoList = accountInfoService.listAllMap();
        modelMap.put("accountInfoList", accountInfoList);

        Long[] postIds = sysUser.getPostIds();

        List<Map<String, String>> accountTypeList = null;
        if (sysUser.isAdmin()){
            accountTypeList = AccountTypeEnum.getListMap();
        }else{
            accountTypeList = AccountTypeEnum.getListMapByPostId(JSON.parseArray(JSON.toJSONString(postIds), Long.class));
        }
        modelMap.put("itemAccountInfoList", accountTypeList);

        return prefix + "/add";
    }

    /**
     * 新增保存账户入账申请
     */
    @PostMapping("/getTypeData/{accountType}")
    @ResponseBody
    public AjaxResult getTypeData(@PathVariable("accountType") String accountType)
    {
        SysUser sysUser = getSysUser();
        List<Map<String, Object>> itemAccountInfoList = new ArrayList<>();

        if (StrUtil.equals(accountType, AccountTypeEnum.SPECIAL.getValue())){
            AccountItemSpecial accountItemSpecial = new AccountItemSpecial();
            if (!sysUser.isAdmin()){
                accountItemSpecial.setOwnerId(sysUser.getUserId());
            }
            itemAccountInfoList = accountItemSpecialService.selectAccountInfoMapList(accountItemSpecial);
        }else if (StrUtil.equals(accountType, AccountTypeEnum.ACCOUNT.getValue())){
            itemAccountInfoList = accountInfoService.listAllMap();
        }

        // 根据账户类型，获取操作类型
        List<Map<String, Object>> actionTypeList = ActionTypeEnum.getListMapByAccountType(accountType);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("itemAccountInfoList", itemAccountInfoList);
        jsonObject.put("actionTypeList", actionTypeList);

        return AjaxResult.success(jsonObject);
    }

    /**
     * 新增保存账户入账申请
     */
    @RequiresPermissions("account:record:add")
    @Log(title = "账户入账申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AccountApplyRecord accountApplyRecord)
    {

        SysUser sysUser = getSysUser();
        accountApplyRecord.setCreatorId(String.valueOf(sysUser.getUserId()));
        accountApplyRecord.setCreatorName(sysUser.getUserName());
        return accountApplyRecordService.insertAccountApplyRecord(accountApplyRecord);
    }

    /**
     * 修改账户入账申请
     */
    @RequiresPermissions("account:record:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        AccountApplyRecord accountApplyRecord = accountApplyRecordService.selectAccountApplyRecordById(id);
        accountApplyRecord.setItemAccountType(AccountTypeEnum.getLabelByValue(accountApplyRecord.getItemAccountType()));
        accountApplyRecord.setActionType(ActionTypeEnum.getLabelByValue(accountApplyRecord.getActionType()));

        mmap.put("accountApplyRecord", accountApplyRecord);

        List<Map<String, String>> statusList = RecordStatusEnum.getListEditMap();
        mmap.put("statusList", statusList);

        List<Map<String, Object>> accountInfoList = accountInfoService.listAllMap();
        mmap.put("accountInfoList", accountInfoList);

        return prefix + "/edit";
    }

    /**
     * 入账申请  详情
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        AccountApplyRecord accountApplyRecord = accountApplyRecordService.selectAccountApplyRecordById(id);

        ApplyRecordVO applyRecordVO = BeanUtil.copyProperties(accountApplyRecord, ApplyRecordVO.class);
        applyRecordVO.setItemAccountTypeStr(AccountTypeEnum.getLabelByValue(accountApplyRecord.getItemAccountType()));
        applyRecordVO.setActionTypeStr(ActionTypeEnum.getLabelByValue(accountApplyRecord.getActionType()));
        mmap.put("applyRecordVO", applyRecordVO);

        return prefix + "/detail";
    }

    /**
     * 修改保存账户入账申请
     */
    @RequiresPermissions("account:record:edit")
    @Log(title = "账户入账申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AccountApplyRecord accountApplyRecord)
    {
        return toAjax(accountApplyRecordService.updateAccountApplyRecord(accountApplyRecord));
    }

    /**
     * 删除账户入账申请
     */
    @RequiresPermissions("account:record:remove")
    @Log(title = "删除入账申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        AccountApplyRecord accountApplyRecord = new AccountApplyRecord();
        accountApplyRecord.setId(Long.valueOf(ids));

        return toAjax(accountApplyRecordService.deleteAccountApplyRecordByIds(accountApplyRecord));
    }

    /**
     * 入账操作
     */
    @RequiresPermissions("account:record:enterAccount")
    @PostMapping("/enterAccount")
    @ResponseBody
    public AjaxResult enterAccount(@RequestParam("recordId") String recordId)
    {
        AccountApplyRecord accountApplyRecord = accountApplyRecordService.selectAccountApplyRecordById(Long.valueOf(recordId));
        if (ObjectUtil.isEmpty(accountApplyRecord)){
            return AjaxResult.error("入账申请记录为空");
        }
        if (StrUtil.equals(ActionTypeEnum.CZ.getValue(), accountApplyRecord.getActionType()) ||
                StrUtil.equals(ActionTypeEnum.ADJUST.getValue(), accountApplyRecord.getActionType()) ||
                StrUtil.equals(ActionTypeEnum.TK.getValue(), accountApplyRecord.getActionType())){
            if (StrUtil.isEmpty(accountApplyRecord.getMainAccountId())){
                return AjaxResult.error("充值/调账/退款的总账信息不能为空");
            }
        }


        SysUser sysUser = getSysUser();

        EntryAccountParam entryAccountParam = new EntryAccountParam();
        entryAccountParam.setRecordId(recordId);
        entryAccountParam.setOperatorId(String.valueOf(sysUser.getUserId()));
        entryAccountParam.setOperatorName(sysUser.getUserName());

        return marketApiService.entryAccount(entryAccountParam);
    }

    /**
     * 拒绝入账 ， 返回到待确认状态
     * @param recordId
     * @return
     */
    @RequiresPermissions("account:record:refuseEnter")
    @PostMapping("/refuseEnter")
    @ResponseBody
    public AjaxResult refuseEnter(@RequestParam("recordId") String recordId)
    {
        return toAjax(accountApplyRecordService.refuseEnter(recordId));
    }

    /**
     * 申请入账
     * @param recordId
     * @return
     */
    @RequiresPermissions("account:record:applyEnter")
    @PostMapping("/applyEnter")
    @ResponseBody
    public AjaxResult entryAccount(@RequestParam("recordId") String recordId)
    {

        AccountApplyRecord accountApplyRecord = accountApplyRecordService.selectAccountApplyRecordById(Long.valueOf(recordId));
        if (ObjectUtil.isEmpty(accountApplyRecord)){
            return AjaxResult.error("入账申请记录为空");
        }
        if (StrUtil.equals(ActionTypeEnum.CZ.getValue(), accountApplyRecord.getActionType()) ||
                StrUtil.equals(ActionTypeEnum.ADJUST.getValue(), accountApplyRecord.getActionType())){
            if (StrUtil.isEmpty(accountApplyRecord.getMainAccountId())){
                return AjaxResult.error("充值/调账的总账信息不能为空");
            }
        }

        AccountApplyRecord updateEntity = new AccountApplyRecord();
        updateEntity.setId(Long.valueOf(recordId));
        updateEntity.setStatus(RecordStatusEnum.WAIT_HANDLE.getValue());
        updateEntity.setUpdateTime(new Date());
        int i = accountApplyRecordService.updateAccountApplyRecord(updateEntity);

        if (i > 0){
            // 申请入账更新成功，进行消息通知
            messageNoticeService.noticeMsgHandle(MessageTypeEnum.BILL_ENTER_WARNING, Arrays.asList(recordId), null);
        }

        return toAjax(i);
    }

}
